<template>
    <ul class= "city-alphabet">
        <li
        class= "alphabet"
        v-for= 'item in letters'
        :key= "item"
        :ref= "item"
        @click= "handleLetterClick"
        @touchstart= 'handleStart'
        @touchmove.prevent= 'handleMove'
        @touchend= 'handleEnd'
        >
            {{item}}
        </li>
    </ul>
    <!-- @touchmove.prevent取消默认行为，解决手机整个屏幕滚动的bug -->
</template>
<script>
export default {
    name: 'city-alphabet',
    data() {
        return {
            touchTruthy: false,
            starty: 0,
            timer: null
        }
    },
    props: {
        cities: Object
    },
    computed: {
        letters() {
            const letters = []
            for (let i in this.cities) {
                letters.push(i)
            }
            return letters
        }
    },
    methods: {
        handleLetterClick(e) {
            this.$emit('letterChange', e.target.innerText)
            // e.target.innerText DOM的知识，不要忘
        },
        handleStart() {
            this.touchTruthy = true
        },
        handleEnd() {
            this.touchTruthy = false
        },
        handleMove(e) {
            if (this.touchTruthy) {
                //字母元素(.alphabet)外边框到包含元素(.city-alphabet)内边框的距离
                if (this.timer) {
                    clearTimeout(this.timer)
                }
                //在timer为 空 时执行的操作会延迟16ms执行，之后在这之间所有的操作会被clearTimeout阻止
                this.timer = setTimeout(() => {
                    //e.touches为dom的故有属性
                    let touchy = e.touches[0].clientY - 75
                    let index = Math.floor((touchy - this.starty) / 20)
                    if (0 <= index && index < this.letters.length) {
                        //传递给City组件，再由父组件传给list组件
                        this.$emit('letterChange', this.letters[index])
                    }
                }, 8)
            }
        }
    },
    updated() {
        this.starty = this.$refs['A'][0].offsetTop
    }
}
</script>

<style lang= "stylus" scoped>
@import '../../../assets/styles/varibles.styl';
.city-alphabet
    display: flex
    flex-direction: column
    justify-content: center
    position: absolute
    top: 1.58rem
    right: 0
    bottom: 0
    width: .4rem
    .alphabet
        line-height: .4rem
        text-align: center
        color: $bgColor
</style>
